//
//  RegionChooseViewController.m
//  OA
//
//  Created by yy on 17/7/20.
//  Copyright © 2017年 yy. All rights reserved.
//

#import "RegionChooseViewController.h"
#import "AreaModel.h"
@interface LazyScrollViewCustomView : UILabel<TMMuiLazyScrollViewCellProtocol>

@end

@implementation LazyScrollViewCustomView

- (void)mui_prepareForReuse
{
    NSLog(@"%@", [NSString stringWithFormat:@"%@ - Prepare For Reuse",self.text]);
}

- (void)mui_didEnterWithTimes:(NSUInteger)times
{
    NSLog(@"%@", [NSString stringWithFormat:@"%@ - Did Enter With Times - %lu",self.text,(unsigned long)times]);
}

- (void)mui_afterGetView
{
    NSLog(@"%@", [NSString stringWithFormat:@"%@ - AfterGetView",self.text]);
}
@end



@interface RegionChooseViewController ()<TMMuiLazyScrollViewDataSource,UIScrollViewDelegate,UISearchBarDelegate>
{
    NSMutableArray * rectArray;
}
@property (nonatomic,strong)TMMuiLazyScrollView *detailScrollview;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (weak, nonatomic) IBOutlet UILabel *areaL;

@property (nonatomic,strong)NSMutableArray *arrOfCity;
@property (nonatomic,strong)NSMutableArray *arrOfCityStr;
@property (nonatomic,strong)NSMutableArray *arrOfTown;
@property (nonatomic,strong)NSMutableArray *arrOfTownStr;
@property (nonatomic,strong)NSMutableArray *arrOfFindByName;
@property (nonatomic,strong)NSMutableArray *arrOfFindByNameStr;
@end



@implementation RegionChooseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.title = @"选择区域";
    self.areaL.text = [NSString stringWithFormat:@"当前区域：%@",_regionName];
    _searchBar.delegate = self;
    _detailScrollview.dataSource = self;
    [self initOfDataSouce];
    [self initializeUserInterface];
}
- (void)initOfDataSouce{
    _arrOfCity = [NSMutableArray array];
    _arrOfTown = [NSMutableArray array];
    [self regionDataWithIndex:@"1"];
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (_searchBar.text.length>0) {
        [self regionFindByName];
    }else{
        [self regionDataWithIndex:@"1"];
    }
    
}


- (void)regionFindByName{
    _arrOfFindByName = [NSMutableArray array];
    _arrOfFindByNameStr = [NSMutableArray array];
    NSMutableDictionary *parm = [NSMutableDictionary dictionary];
    NSString *str = _searchBar.text;
    [parm setObject:str forKey:@"name"];
    [[ToolOfNetWork sharedTools]YrequestURL:oa_regionfindByName withParams:parm finished:^(id responsObject, NSError *error) {
        if (_Success) {
            _arrOfFindByName = [NSMutableArray arrayWithArray:responsObject[@"data"]];
            for (int i = 0; i<_arrOfFindByName.count; i++) {
                [_arrOfFindByNameStr addObject:[NSString stringWithFormat:@"%@",_arrOfFindByName[i][@"name"]]];
            }
              [self initializeUserInterfaceOver];
        }else{
            Y_MBP_Error
        }
    }];
    
    
}
- (void)regionDataWithIndex:(NSString *)indexStr{
    NSString *url = oa_getCityList;
    if ([indexStr isEqualToString:@"1"]) {
        url = oa_getCityList;
    }else{
        url = oa_getTwonList;
    }
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    [[ToolOfNetWork sharedTools]YrequestURL:url withParams:parms finished:^(id responsObject, NSError *error) {
        if (_Success) {
            if ([indexStr isEqualToString:@"1"]) {
                _arrOfCity = [NSMutableArray arrayWithArray:responsObject[@"data"]];
                _arrOfCityStr = [NSMutableArray array];
                for (int i = 0 ; i < _arrOfCity.count; i ++) {
                    [_arrOfCityStr addObject:[NSString stringWithFormat:@"%@",_arrOfCity[i][@"name"]]];
                }
                [_arrOfCityStr insertObject:@"主城" atIndex:0];
                [self regionDataWithIndex:@"2"];
            }else{
                _arrOfTown = [NSMutableArray arrayWithArray:responsObject[@"data"]];
                _arrOfTownStr = [NSMutableArray array];
                for (int i = 0 ; i < _arrOfTown.count; i ++) {
                   [_arrOfTownStr addObject:[NSString stringWithFormat:@"%@",_arrOfTown[i][@"name"]]];
                }
                [_arrOfTownStr insertObject:@"区县" atIndex:0];
                [self initializeUserInterfaceOver];
                
            }
        }else{
            Y_MBP_Error
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    //观察者的移除
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)initializeUserInterface{
    _detailScrollview = [[TMMuiLazyScrollView alloc]init];
    _detailScrollview.dataSource = self;
    _detailScrollview.backgroundColor = BackWiteColor;
 
    [self.view addSubview:self.detailScrollview];
    [_detailScrollview mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_areaL.mas_bottom).offset(10);
        make.centerX.equalTo(self.view);
        make.width.equalTo(self.view.mas_width);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
}

- (void)initializeUserInterfaceOver{
    rectArray  = [[NSMutableArray alloc] init];
    if (_searchBar.text.length == 0) {
        for (int i = 0; i < 1 ; i++) {
            [rectArray addObject:[NSValue valueWithCGRect:CGRectMake(10, 10+i*80 + 2 , 80,60)]];//60+10+2
        }
        for (int i = 1; i < _arrOfCityStr.count ; i++) {
            [rectArray addObject:[NSValue valueWithCGRect:CGRectMake(((i-1)%3)*Y_mainW/3+20 ,80+(i-1)/3*70, (Y_mainW-30)/3-20,50)]];//50
        }
        for (int i = 0; i < 1; i++) {
            [rectArray addObject:[NSValue valueWithCGRect:CGRectMake(10, (_arrOfCityStr.count/3+1)*80-30, 80,60)]];
        }
        for (int i = 1; i < _arrOfTownStr.count ; i++) {
            [rectArray addObject:[NSValue valueWithCGRect:CGRectMake(((i-1)%3)*Y_mainW/3+20 ,60+(_arrOfCityStr.count/3+1)*80+(i-1)/3*70, (Y_mainW-30)/3-20,50)]];
        }
        
        _detailScrollview.contentSize = CGSizeMake(Y_mainW,(_arrOfCityStr.count+_arrOfTownStr.count)/3*90+100);
    }else{
//        for (int i = 0; i < 1 ; i++) {
//            [rectArray addObject:[NSValue valueWithCGRect:CGRectMake(10, 10+i*80 + 2 , 80,60)]];//60+10+2
//        }
        for (int i = 1; i < _arrOfFindByName.count+1 ; i++) {
            [rectArray addObject:[NSValue valueWithCGRect:CGRectMake(((i-1)%3)*Y_mainW/3+20 ,80+(i-1)/3*70, (Y_mainW-30)/3-20,50)]];//50
            _detailScrollview.contentSize = CGSizeMake(Y_mainW,(_arrOfFindByName.count+_arrOfFindByNameStr.count)/3*90+100);
        }
    }
    [MBProgressHUD hideHUD];
    [self.detailScrollview reloadData];
    [self.detailScrollview scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
    [self.view endEditing:YES];
}

//STEP 2 implement datasource delegate.
- (NSUInteger)numberOfItemInScrollView:(TMMuiLazyScrollView *)scrollView
{
    return rectArray.count;
}

- (TMMuiRectModel *)scrollView:(TMMuiLazyScrollView *)scrollView rectModelAtIndex:(NSUInteger)index
{
    CGRect rect = [(NSValue *)[rectArray objectAtIndex:index]CGRectValue];
    TMMuiRectModel *rectModel = [[TMMuiRectModel alloc]init];
    rectModel.absoluteRect = rect;
    rectModel.muiID = [NSString stringWithFormat:@"%ld",index];
    
    return rectModel;
}
#pragma mark —————— label显示
- (UIView *)scrollView:(TMMuiLazyScrollView *)scrollView itemByMuiID:(NSString *)muiID
{
    
    
    LazyScrollViewCustomView *label = (LazyScrollViewCustomView *)[scrollView dequeueReusableItemWithIdentifier:@"testView"];
    label.numberOfLines = 0;
    NSInteger index = [muiID integerValue];
    if (!label)
    {
        label = [[LazyScrollViewCustomView alloc]initWithFrame:[(NSValue *)[rectArray objectAtIndex:index]CGRectValue]];
        label.textAlignment = NSTextAlignmentCenter;
        label.reuseIdentifier = @"testView";
    }
    label.frame = [(NSValue *)[rectArray objectAtIndex:index]CGRectValue];
    if (_searchBar.text.length>0) {
         //模糊搜索
        label.text = [NSString stringWithFormat:@"%@",_arrOfFindByNameStr[index]];
        label.layer.borderColor = [[UIColor blackColor]CGColor];
        label.layer.borderWidth = 1;
        label.userInteractionEnabled = YES;

        
    }else{
        if (index == 0 || index == _arrOfCityStr.count) {//主城区县两个
            label.backgroundColor = [UIColor clearColor];
            label.layer.borderWidth = 0;
            label.userInteractionEnabled = NO;
            if (index == 0) {
                label.text = _arrOfCityStr[0];
            }else{
                label.text = _arrOfTownStr[0];
            }
        }else{//内容数据
            if (index >= _arrOfCityStr.count) {
                
                label.text = [NSString stringWithFormat:@"%@",_arrOfTownStr[index-_arrOfCityStr.count]];
            }else{
                label.text = [NSString stringWithFormat:@"%@",_arrOfCityStr[index]];
            }
            
            label.layer.borderColor = [[UIColor blackColor]CGColor];
            label.layer.borderWidth = 1;
            label.userInteractionEnabled = YES;
        }
       

    }
    label.textColor = [UIColor blackColor];
    [scrollView addSubview:label];
    label.userInteractionEnabled = YES;
    
    [label addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click:)]];
    return label;
}

#pragma mark —————— 点击事件
- (void)click:(UIGestureRecognizer *)recognizer
{
    LazyScrollViewCustomView *label = (LazyScrollViewCustomView *)recognizer.view;
    int  index = [label.muiID intValue];
    NSDictionary *dic = [NSMutableDictionary dictionary];
    if (_searchBar.text.length > 0) {
        dic = [NSDictionary dictionaryWithDictionary: _arrOfFindByName[index]];
        NSLog(@"=f=%d,%@",index,[dic[@"name"] kdtk_stringByReplaceingUnicode]);
    
        
    }else{
        if (index >= _arrOfCityStr.count) {
            
            dic = [NSDictionary dictionaryWithDictionary: _arrOfTown[index- _arrOfCity.count-2]];
            NSLog(@">>>>%d,%@",index,[dic[@"name"] kdtk_stringByReplaceingUnicode]);
        }else{
            
            dic = [NSDictionary dictionaryWithDictionary: _arrOfCity[index-1]];
            NSLog(@"===%d,%@",index,[dic[@"name"] kdtk_stringByReplaceingUnicode]);
        }
        
    }
   
    [self notice:dic];

}

#pragma mark —————— 发送通知消息
- (void)notice:(NSDictionary*)regionDic{
    //创建一个消息对象
    NSNotification * notice = [NSNotification notificationWithName:@"regionChooseInfo" object:nil userInfo:regionDic];
    //发送消息
    [[NSNotificationCenter defaultCenter]postNotification:notice];
    [self.navigationController popViewControllerAnimated:YES];
    
}


@end
